package com.basic.webframe;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import com.basic.common.FuncStatic; 

public class HtmlBuilder {
	private static Logger logger = Logger.getLogger ( HtmlBuilder.class.getName () );
	private static String ENCODE = null;
	private static String WEBFOLDER = null;
	private String template = null;
	private Context context = new VelocityContext();
	private HtmlBuilder () {
		context.put("g_path", "/" + WEBFOLDER +"/view");
	} 
	
	public static void init(String webFolder ,String encode, boolean ifVelocityCache,String[] macros){
		ENCODE = encode;
//		HOST = host;
		WEBFOLDER = webFolder;
		// 初始化 Velocity
		Velocity.addProperty(Velocity.ENCODING_DEFAULT, ENCODE);
		Velocity.addProperty(Velocity.INPUT_ENCODING, ENCODE);
		Velocity.addProperty(Velocity.OUTPUT_ENCODING, ENCODE);
		Velocity.addProperty("userdirective",VelocityPackage.class.getName());
		Velocity.addProperty("file.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		if(macros != null){
			for(String macro : macros){
				Velocity.addProperty(Velocity.VM_LIBRARY, "/" + webFolder + macro);
			}
		}
		if (ifVelocityCache ) { 
			Velocity.addProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, true);
		} else {
			Velocity.addProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, false);
		}
		Velocity.init();
	}
	public static HtmlBuilder instance(String templatePath){
		HtmlBuilder hb = new HtmlBuilder();
		hb.template =  "/" + WEBFOLDER +"/view/"+templatePath;
		return hb;
	}
	public void setValue(String name,Object value){
		context.put(name, value);
	}
	public void setValue(Map<String, String> value){
		for(String key : value.keySet())
			context.put(key, value.get(key));
	}
	 
	public void setContext(Context context){
		this.context = context;
	}
	public String html(){
		StringWriter sw = new StringWriter();
		try { 
			Velocity.mergeTemplate(this.template, ENCODE, this.context, sw);
		} catch (Exception e) {
			logger.error(FuncStatic.errorTrace(e));
		} 
		return sw.toString();
			
	}
	public String html(String node){
		return FuncStatic.searchString(html(), FuncStatic.format("<!--{0} start-->([\\s\\S]*?)<!--{0} end-->", node));
	}
	public void html(Writer writer){ 
		try { 
			Velocity.mergeTemplate(this.template, ENCODE, this.context, writer);
		} catch (Exception e) {
			logger.error(FuncStatic.errorTrace(e));
		} 
	}
	 
	public String toString(){
		return html();
	}
 
}
